package fr.vod.ihm.videoshareucp;

import java.io.File;
import java.io.FilenameFilter;

import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnErrorListener;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.IInterface;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.preference.PreferenceManager;
import android.support.v4.widget.SlidingPaneLayout;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.MediaController;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
import fr.vod.ihm.adapter.ExpandableListAdapter;
import fr.vod.ihm.adapter.MyVideoView;
import fr.vod.ihm.adapter.MyVideoView.PlayPauseListener;
import fr.vod.ihm.adapter.MyVideoView.SeekListener;
import fr.vod.ihm.adapter.VideoController;
import fr.vod.threads.ServiceMulticastHeartbeat;
import fr.vod.threads.ServiceMulticastVideo;
import fr.vod.threads.TransferTask;
import fr.vod.util.LogHelper;
import fr.vod.util.MySettings;
import fr.vod.videoshareucp.R;

public class MainActivity extends Activity implements OnClickListener {

	// Pour settings
	private static int CODE_RETOUR = 1;
    private AlertDialog.Builder builder;
	
	public String pathVideo = null;
	Button modeButton;
	TextView informationFile;
	Button cancelButton;
	Button browseButton;
	public MyVideoView vv;
	private MyVideoView vvfull;
	private MediaController mc2;
	private VideoController mc;
	
	ActionBar actionBar;
	boolean showActionBar = true;
	
	SlidingPaneLayout pane;
	RelativeLayout relativeVideo;
	RelativeLayout relativeControl;
	RelativeLayout relativeFile;
    LinearLayout linearNetwork;
    LinearLayout linearTransfert;
    RelativeLayout fullLayout;
    public ScrollView scrollView;
    public TextView textViewScroll;
    
    private boolean isServer = false;
	protected boolean isFullScreenLayout = false;
	
    
    // Objets pour la liste du linearNetworkPane
	ExpandableListAdapter listAdapter;
	ExpandableListView expListView;
	
	
	//Objets pour la syncrhonisation video
	public static final int MESSAGE_INIT = 1;
	private Messenger serviceMessenger;
	protected boolean flagSyncBind;
	public boolean isSyncBinded = false;
	Messenger messenger = new Messenger(new IncomingSyncHandler());
	Intent serviceIntent;
	private TransferTask trTask;
	
	/// tag des logs
	private final static String logTag 	=   MainActivity.class.getName();
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		LogHelper.entree(logTag, "onCreate");	
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		LogHelper.information(logTag, "Debugging " + android.os.Build.MODEL);
		initUiElement();
		initMediaViewControl();
		initAdapterElement();
		initControlButton();
		initVideoSync();   
	}

	
	private void initVideoSync() {
		serviceIntent = new Intent(this, ServiceMulticastVideo.class);
		// bind pour echanger des messages
		startService(serviceIntent);
	}

	private void initUiElement() {
		relativeVideo = (RelativeLayout)findViewById(R.id.relativeVideo);
		relativeControl = (RelativeLayout)findViewById(R.id.relativeControl);
		relativeFile = (RelativeLayout)findViewById(R.id.relativeFile);
	    linearNetwork = (LinearLayout)findViewById(R.id.linearNetworkPane);
	    linearTransfert = (LinearLayout)findViewById(R.id.linearTransfertPane);
	    fullLayout = (RelativeLayout)findViewById(R.id.fullScreenLayout);
	    scrollView = (ScrollView) findViewById(R.id.scrollViewInfo);
	    textViewScroll = (TextView) findViewById(R.id.textViewScroll);
		pane = (SlidingPaneLayout)findViewById(R.id.slidingPaneLayout);
		modeButton = (Button)findViewById(R.id.streamButton);
		informationFile = (TextView)findViewById(R.id.informationFile);
		cancelButton = (Button)findViewById(R.id.cancelButton);
		browseButton = (Button)findViewById(R.id.browseButton);
		
		vv = (MyVideoView) findViewById(R.id.videoView1);		
		vv.setZOrderOnTop(true);
		pane.setPanelSlideListener(new PaneListener());
		linearTransfert.requestFocus();
		
	}
	
	private void initMediaViewControl(){
		//vv = new MyVideoView(MainActivity.this);
		//vvfull = new MyVideoView(MainActivity.this);
		mc = new VideoController(MainActivity.this);
		mc2 = new MediaController(MainActivity.this);
	}
	
	private void initAdapterElement() {
		// initialisation de la liste du gridNetwork
		expListView = (ExpandableListView) findViewById(R.id.listNetworkInfo);
        listAdapter = new ExpandableListAdapter(getBaseContext(), android.os.Build.MODEL, getLocalIpAddress(), getHeartbeatLogsPreferences(), getVideoSyncLogsPreferences());
        expListView.setAdapter(listAdapter);
        
        if (android.os.Build.MODEL.contains("ASUS")) {
        	for (int i = 0; i < listAdapter.getGroupCount(); i++)
        		expListView.expandGroup(i);
        }
        
        pane.openPane();
		linearTransfert.setVisibility(View.VISIBLE);
		relativeFile.setVisibility(View.INVISIBLE);
		linearNetwork.setVisibility(View.INVISIBLE);
		//expListView.requestFocus();
	}

	public void startVideoPlayer(String path) {
		vv.setVideoPath(path);
		vv.setOnErrorListener(new OnErrorListener () {
		    @Override
		    public boolean onError(MediaPlayer mp, int what, int extra) {
		        LogHelper.erreur("prepareVideoPlayer(String path)", "Error playing video");
		        Toast toast = Toast.makeText(getBaseContext(),R.string.toastVideoError ,Toast.LENGTH_LONG);
		        toast.show();
		        return true;
		    }
		});
			
		mc.setActivated(false);
		mc.setAnchorView(findViewById(R.id.mediaController));
		//mc.setBackground(getResources().getDrawable(R.drawable.border));
		vv.setMediaController(mc);
		mc.setMediaPlayer(vv);
		vv.setOnTouchListener(new OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if (mc.isActivated()){
					mc.setVisibility(View.INVISIBLE);
					mc.show(200);
					mc.setActivated(false);
				}
				else {
					mc.setActivated(true);
					mc.setVisibility(View.VISIBLE);
					mc.show(200);
					
				}
				return false;
			}
		});
		
		
		mc.fullScreenButton.setOnClickListener(new OnClickListener() {
			
			private int currentVideoPosition;

			@Override
			public void onClick(View v) {
				mc.setVisibility(View.INVISIBLE);
				currentVideoPosition = vv.getCurrentPosition();
				isFullScreenLayout = true;
				actionBar = getActionBar();
				actionBar.hide();
				
				setContentView(R.layout.full_screen);
				vvfull = (MyVideoView) findViewById(R.id.videoViewFull);				
				vvfull.setMediaController(mc2);
				mc2.setMediaPlayer(vvfull);
				vvfull.requestFocus();
				
				if(!pathVideo.isEmpty()){
					vvfull.setVideoPath(Environment.getExternalStorageDirectory().getPath()+"/Movies/"+pathVideo);
					vvfull.start();
					vvfull.seekTo(currentVideoPosition);
				}
				vvfull.setPlayPauseListener(new PlayPauseListener() {
					@Override
					public void onPlay() {
						LogHelper.information("onPlay", "play");
						sendMessageToSyncService("PLAY");
					}
					@Override
					public void onPause() {
						LogHelper.information("onPause", "pause");
						sendMessageToSyncService("PAUSE");
					}
				});
				vvfull.setSeekListener(new SeekListener() {

			        @Override
			        public void onSeekTo(boolean ffwdrwd) {
			            if(ffwdrwd){
			            	LogHelper.information(logTag, "backWard");
			            	sendMessageToSyncService("TIME");
			            }
			            else{
			            	LogHelper.information(logTag, "forWard");
			            	sendMessageToSyncService("TIME");
			            }             
			        }
			     });
			    vvfull.setOnTouchListener(new OnTouchListener() {
					@Override
					public boolean onTouch(View v, MotionEvent event) {
						ActionBar actionBar = getActionBar();
						if(showActionBar){
							actionBar.setDisplayHomeAsUpEnabled(true);
							actionBar.show();
							showActionBar = false;
						}
						else {
							actionBar.hide();
							
							showActionBar = true;
						}
						 
						return false;
					}
				});	
			}
		});
		
	vv.setPlayPauseListener(new PlayPauseListener() {
		@Override
		public void onPlay() {
			LogHelper.information("onPlay", "play");
			sendMessageToSyncService("PLAY");
			
		}
		@Override
		public void onPause() {
			LogHelper.information("onPause", "pause");
			sendMessageToSyncService("PAUSE");
		}
	});
	
	vv.setSeekListener(new SeekListener() {

        @Override
        public void onSeekTo(boolean ffwdrwd) {
            if(ffwdrwd){
            	LogHelper.information(logTag, "backWard");
            	sendMessageToSyncService("TIME");
            }
            else{
            	LogHelper.information(logTag, "forWard");
            	sendMessageToSyncService("TIME");
            }             
        }

    });
		
	}

	/**
	 * methode permetant d'initaliser les boutons de controle : browse et stream 
	 */
	private void initControlButton() {
		final Button browseButton=(Button)findViewById(R.id.browseButton);
		browseButton.setFocusable(true);
		browseButton.setOnClickListener(this);

		final Button streamButton = (Button) findViewById(R.id.streamButton);
		streamButton.setFocusable(true);
		streamButton.setOnClickListener(this);
		
		final Button cancelButton = (Button) findViewById(R.id.cancelButton);
		cancelButton.setFocusable(true);
		cancelButton.setOnClickListener(this);
		isServer=false;
		
	}
	

	@Override
	public void onClick(View v) {
		LogHelper.information(logTag, "onClick");
		switch(v.getId()) {
		case R.id.browseButton:
			LogHelper.information(logTag, "browse");
			actionBrowse();
			break;
			
		case R.id.streamButton:
			LogHelper.information(logTag, "stream");
			Toast toast;
			
			relativeControl.setVisibility(View.INVISIBLE);
			pane.setVisibility(View.VISIBLE);
			
			if(isServer){
				 toast = Toast.makeText(getBaseContext(),R.string.toastServerMode ,Toast.LENGTH_SHORT);
				 getActionBar().setDisplayHomeAsUpEnabled(true);
			}
			else{ 
				 toast = Toast.makeText(getBaseContext(),R.string.toastClientMode ,Toast.LENGTH_SHORT);
				 getActionBar().setDisplayHomeAsUpEnabled(true);
			}
			toast.setGravity(Gravity.TOP|Gravity.CENTER, 0, 0);
			toast.show();
			
			Intent intent = new Intent(this, ServiceMulticastHeartbeat.class);
			Bundle bundle = new Bundle();
			bundle.putBoolean("isServer", isServer);
			bundle.putBoolean("displayLogs", getHeartbeatLogsPreferences());
			intent.putExtras(bundle);
			startService(intent);
			// Start Receiving Task (For Clients)
			trTask = new TransferTask(this, listAdapter, isServer, pathVideo, getHeartbeatLogsPreferences(), getBlocSizePreferences(), getPacketSizePreferences(), getSubBlocSizePreferences());
			trTask.execute();

			/**
			 * TODO : modifier ce bundle pour qu'il se déplace dans le syncServiceConn
			 */
			Bundle bundleVideo = new Bundle();
			bundle.putBoolean("displayLog", getVideoSyncLogsPreferences());
			serviceIntent.putExtras(bundleVideo);
			isSyncBinded = bindService(serviceIntent, syncServiceConn, Context.BIND_AUTO_CREATE);
			
			if (isSyncBinded == true) {
				LogHelper.information(logTag, "Service correctly binded.");
			}
			else
				LogHelper.erreur(logTag, "Activity not binded to service");
			
			break;
			
		case R.id.cancelButton:
			//TODO ajouter coupure thread
			LogHelper.entree(logTag, "cancel button");
			setContentView(R.layout.activity_main);
	    	initUiElement();
	    	initControlButton();
	    	initAdapterElement();
			mc.setVisibility(View.INVISIBLE);
			modeButton.setText("Client");
			isServer = false;
			break;
			
		default:
			break;
		}
	}

	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}
	
	
    private void sendMessageToSyncService(String message) {
    	Message msg = Message.obtain(null, ServiceMulticastVideo.MESSAGE_CMD, 0, 0);
    	Bundle bundle = msg.getData();
    	bundle.putString("CMD", message);
    	
    	if(isFullScreenLayout){
    		bundle.putInt("TIME", vvfull.getCurrentPosition());
    		bundle.putLong("TIMESTAMP", System.currentTimeMillis());
    	}
    	else {
    		bundle.putInt("TIME", vv.getCurrentPosition());
    		bundle.putLong("TIMESTAMP", System.currentTimeMillis());
    	}
    	
    	try {
    		if (flagSyncBind) {
	    		listAdapter.appendToSynchroLog("-->"+msg.getData().toString().substring("bundle".length())+"\n");
	    		serviceMessenger.send(msg);
    		}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	
    private  ServiceConnection syncServiceConn = new ServiceConnection() {

		public void onServiceConnected(ComponentName className,
                IBinder serviceBinder) {
    		LogHelper.information(logTag, "onServiceConnected");	
        	
    		// Recuperation du messenger
    		serviceMessenger = new Messenger(serviceBinder);
            
            flagSyncBind = true;
            
            // preparation du message
             Message msg = Message.obtain(null, ServiceMulticastVideo.MESSAGE_TYPE, 0, 0);

             // enregistrement du handler de l'activite
             msg.replyTo = messenger;
            		 
            try {
            	serviceMessenger.send(msg);
            	LogHelper.information(logTag, "Message sended : " + msg);
           	
            } catch (RemoteException e) {
                e.printStackTrace();
            }
            
        }


        public void onServiceDisconnected(ComponentName arg0) {
    		LogHelper.information(logTag, "onServiceDisconnected");	
    		flagSyncBind = false;
        }
	};

    
    /**
	 * Handler des messages entrant
	 *
	 */
    class IncomingSyncHandler extends Handler {
    	
        
        IncomingSyncHandler(){
    		LogHelper.entree(logTag, "IncomingSyncHandler");	
        }
        
        @Override
        public void handleMessage(Message msg) {
           	LogHelper.entree(logTag, "handleMessage");
           	
           	Bundle bundle = msg.getData();
           	
            switch (msg.what) {
            case 	MESSAGE_INIT:
            	String incomingMessage = bundle.getString("flag");
            	LogHelper.information(logTag, "message = " + incomingMessage);
            	
            	break;
            case ServiceMulticastVideo.MESSAGE_CMD:
            	String cmd = bundle.getString("CMD");
            	listAdapter.appendToSynchroLog("<--"+bundle.toString().substring("bundle".length())+"\n");
				//scrollViewReceived.fullScroll(ScrollView.FOCUS_DOWN);
            	if (cmd.contains("PLAY")) {
            		LogHelper.information(logTag, "PLAY received from Service");
            		String str[] = cmd.split("\\|");
            		for (int i = 0; i < str.length; i ++) {
            			LogHelper.information(logTag, "str["+i+"] = " + str[i]);
            		}
            		long delay = (System.currentTimeMillis() - Long.valueOf(str[2]));
            		LogHelper.information(logTag, "Le délai est donc de : " + delay + " ns");
            		vv.seekToFromHandler(Integer.valueOf(str[1]) + (int)delay);
            		vv.startFromHandler();
            		if(vvfull != null){
            			vvfull.startFromHandler();
            			vvfull.seekToFromHandler(Integer.valueOf(str[1]) + (int)delay);
            		}
            	}
            	else if (cmd.contains("PAUSE")) {
            		LogHelper.information(logTag, "PAUSE received from Service");
            		String str[] = cmd.split("\\|");
            		for (int i = 0; i < str.length; i ++) {
            			LogHelper.information(logTag, "str["+i+"] = " + str[i]);
            		}
            		long delay = (System.currentTimeMillis() - Long.valueOf(str[2]));
            		LogHelper.information(logTag, "Le délai est donc de : " + delay + " ms");
            		vv.seekToFromHandler(Integer.valueOf(str[1]) + (int)delay);
            		vv.pauseFromHandler();
            		if(vvfull != null){
            			//vv.seekToFromHandler(Integer.valueOf(str[1]) + (int)delay);
            			vvfull.pauseFromHandler();
            		}
            	}
            	else if (cmd.contains("TIME")){
            		LogHelper.information(logTag, "TIME received from Service");
            		String str[] = cmd.split("\\|");
            		for (int i = 0; i < str.length; i ++) {
            			LogHelper.information(logTag, "str["+i+"] = " + str[i]);
            		}
            		long delay = (System.currentTimeMillis() - Long.valueOf(str[2]));
            		LogHelper.information(logTag, "Le délai est donc de : " + delay + " ms");
            		vv.seekToFromHandler(Integer.valueOf(str[1]) + (int)delay);
            		if(vvfull != null){
            			vvfull.seekToFromHandler(Integer.valueOf(str[1]) + (int)delay);
            		}
            	}
            	break;
            	
            /*case ServiceMulticastVideo.MESSAGE_STAT : 
            		
            	
            	LogHelper.information(logTag, "UPLOAD_SPEED received from Service");
            	tvUploadSpeed.setText(getString(R.string.upload_speed) + bundle.getString("UPLOAD_SPEED"));
            	break;
            	*/
            default:
               super.handleMessage(msg);
               break;
            }
        }
    }	
	
	private String getLocalIpAddress() {
		WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
		int myIp = wifiManager.getConnectionInfo().getIpAddress();

		int intMyIp3 = myIp / 0x1000000;
		int intMyIp3mod = myIp % 0x1000000;
		int intMyIp2 = intMyIp3mod / 0x10000;
		int intMyIp2mod = intMyIp3mod % 0x10000;
		int intMyIp1 = intMyIp2mod / 0x100;
		int intMyIp0 = intMyIp2mod % 0x100;
		String s = String.valueOf(intMyIp0) + "." + String.valueOf(intMyIp1)
				+ "." + String.valueOf(intMyIp2) + "."
				+ String.valueOf(intMyIp3);
		boolean chaineOK = true;
		for (int i = 0; i < s.length(); i++)
			if (s.charAt(i) != '.' && !Character.isDigit(s.charAt(i)))
				chaineOK = false;
		if (!chaineOK)
			s = null;

		return s;
	}
	
	private class PaneListener implements SlidingPaneLayout.PanelSlideListener {
		
		private boolean hasMoved = false;
		
	    @Override
	    public void onPanelClosed(View view) {
	        //LogHelper.entree("PaneListener", "Panel Closed");
	        
	        LinearLayout linearNetwork = (LinearLayout)findViewById(R.id.linearNetworkPane);
	        LinearLayout linearTransfert = (LinearLayout)findViewById(R.id.linearTransfertPane);
	        
	        if(hasMoved) {
	        	linearTransfert.setVisibility(View.INVISIBLE);
	        	linearTransfert.setFocusable(false);
	        	linearTransfert.setClickable(false);
	        		        	
		        linearNetwork.setVisibility(View.VISIBLE);
		        linearNetwork.setFocusable(true);
		        linearNetwork.setClickable(true);
		        linearNetwork.requestFocus();
		        
		        hasMoved=false;
		     }
	        
	     }
	 
	    @Override
	    public void onPanelOpened(View view) {
	    	//LogHelper.entree("PaneListener", "Panel Open");
	    
		     LinearLayout linearNetwork = (LinearLayout)findViewById(R.id.linearNetworkPane);
		     LinearLayout linearTransfert = (LinearLayout)findViewById(R.id.linearTransfertPane);
		     
		     
		     if(hasMoved) {
		    	linearTransfert.setVisibility(View.VISIBLE);
		    	linearTransfert.setFocusable(true);
		    	linearTransfert.setClickable(true);
		    	linearTransfert.requestFocus();
		    	
		     	linearNetwork.setVisibility(View.INVISIBLE);
		     	linearNetwork.setFocusable(false);
		     	linearNetwork.setClickable(false);
		     	
		     	hasMoved=false;
		     }
		     
	    }
	 
	    @Override
	    public void onPanelSlide(View view, float arg1) {
	    	//LogHelper.entree("PaneListener", "Panel slide");
	        hasMoved=true;
	        
	    }
	    
	   
	    }
	
	@Override
	public void onBackPressed() {
		LogHelper.entree(logTag, "onBackPressed()");
		
		if(isFullScreenLayout){
			//this.onStop();
			int saveTimeVideo = vvfull.getCurrentPosition();
	    	setContentView(R.layout.activity_main);
	    	initUiElement();
	    	initControlButton();
	    	initAdapterElement();
	    	actionBar.setDisplayHomeAsUpEnabled(false);
	    	isFullScreenLayout = false;
	    	System.out.println("test "+saveTimeVideo);
	    	vv.seekTo(saveTimeVideo);
	    	vv.start();
    		
    	}
		
		else {
			new AlertDialog.Builder(this)
	        .setMessage("Are you sure you want to exit?")
	        .setCancelable(false)
	        .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
	            public void onClick(DialogInterface dialog, int id) {
	            		MainActivity.this.finish();
	            	}
	                
	        })
	        .setNegativeButton("No", null)
	        .show();
		}
	
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		int saveTimeVideo=0;
	    switch (item.getItemId()) {

	    
	    // Respond to the action bar's Up/Home button

	    //TODO ajouter coupure thread 
	    case android.R.id.home:
	    	LogHelper.information(logTag,"Clic Home button");
	    	if(isFullScreenLayout)
	    		saveTimeVideo = vvfull.getCurrentPosition();
	    	setContentView(R.layout.activity_main);
	    	initUiElement();
	    	initControlButton();
	    	initAdapterElement();
	    	initMediaViewControl();
	    	getActionBar().setDisplayHomeAsUpEnabled(false);
	    	//mc.setVisibility(View.INVISIBLE);
	    	if (isSyncBinded) {
	    		LogHelper.information(logTag, "is still binded");
	    	} else
	    		LogHelper.information(logTag, "not binded anymore");
	    	switch (trTask.getStatus()) {
	    	case PENDING:
	    		LogHelper.information(logTag, "AsyncTask PENDING");
	    		trTask.onDismiss();
	    		break;
	    	case RUNNING:
	    		LogHelper.information(logTag, "AsyncTask RUNNING");
	    		trTask.onDismiss();
	    		break;
	    	case FINISHED:
	    		LogHelper.information(logTag, "AsyncTask FINISHED");
	    		break;
	    	default:
	    			break;
	    	}
	    	LogHelper.information(logTag, "AsyncTask now : " + trTask.getStatus() );
	    	if(isFullScreenLayout){
	    		
	    		LogHelper.information(logTag,"vvfull currentPosition : "+saveTimeVideo);
	    		startVideoPlayer(Environment.getExternalStorageDirectory().getPath()+"/Movies/"+pathVideo);
	    		isFullScreenLayout = false;
	    		informationFile.setText("you choose the file : "+pathVideo);
	    		browseButton.setVisibility(View.INVISIBLE);
	    		modeButton.setVisibility(View.INVISIBLE);
		    	cancelButton.setClickable(false);
		    	cancelButton.setVisibility(View.INVISIBLE);
		    	informationFile.setVisibility(View.INVISIBLE);
	    		cancelButton.setText("Cancel Transfer");
	    		browseButton.setClickable(false);
		    	LogHelper.information(logTag, "video path : "+Environment.getExternalStorageDirectory().getPath()+"/Movies/"+pathVideo);
	    		vv.start();
	    		vv.seekTo(saveTimeVideo);
	    		pane.setVisibility(View.VISIBLE);
	    		LogHelper.information(logTag,"vv start()");
	    	}
	    	
	    	
	        return true;
	    case R.id.action_settings:
	    	startActivityForResult(new Intent(this, MySettings.class), CODE_RETOUR);
	    	return true;
	    case R.id.menu_us: 
	    	AlertDialog.Builder AboutUs = new AlertDialog.Builder(this);
			AboutUs.setTitle("About us");
			AboutUs.setMessage("This application was created by :\n" +
					"\tNicolas Le Menn, \n" +
					"\tDimby Razanakoto,\n" +
					"\t and Alexis Hemled.");
			AlertDialog alert_us = AboutUs.create();
			alert_us.show();
			break;
	    case R.id.menu_help: 
	    	AlertDialog.Builder Help = new AlertDialog.Builder(this);
	    	Help.setTitle("Help");
	    	Help.setMessage("On this screen, you have two choices :\n" +
	    			"\tchoose a file if you want to be a Sever,\n" +
	    			"\tor just click the Client button if you want to be a CLient.");
	    	AlertDialog alert = Help.create();
	    	alert.show();
	    	break;
	    default:
	    	break;
	    }
	    return super.onOptionsItemSelected(item);
	}
	
	public boolean getHeartbeatLogsPreferences() {
    	SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
    	LogHelper.information(logTag, "displayHeartbeatLogs : " + preferences.getBoolean("displayHeartbeatLogs", false));
    	return preferences.getBoolean("displayHeartbeatLogs", false);
    }
	
	public boolean getVideoSyncLogsPreferences() {
    	SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
    	LogHelper.information(logTag, "displayVideoSyncLogs : " + preferences.getBoolean("displayVideoSyncLogs", false));
    	return preferences.getBoolean("displayVideoSyncLogs", false);
    }
	
	public int getBlocSizePreferences() {
    	SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
    	LogHelper.information(logTag, "blocSize = " + preferences.getInt("blocSize", 512));
    	return preferences.getInt("blocSize", 512);
    }
	
	public int getPacketSizePreferences() {
    	SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
    	LogHelper.information(logTag, "packetSize = " + preferences.getInt("packetSize", 512));
    	return preferences.getInt("packetSize", 512);
    }
	
	public int getSubBlocSizePreferences() {
    	SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
    	LogHelper.information(logTag, "subBlocSize = " + preferences.getInt("subBlocSize", 64));
    	return preferences.getInt("subBlocSize", 64);
    }
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == CODE_RETOUR)
			Toast.makeText(this, "Settings saved", Toast.LENGTH_SHORT)
					.show();
		super.onActivityResult(requestCode, resultCode, data);
	}
	
	@Override
	protected void onPause() {
		LogHelper.entree(logTag, "onPause");
		super.onPause();
	}
	
	@Override
	protected void onResume() {
		LogHelper.entree(logTag, "onResume");
		super.onResume();
	}
	
	@Override
	protected void onStop() {
		LogHelper.entree(logTag, "onStop");
		super.onStop();
		//unbindService(syncServiceConn);
	}
	
	/*methode � ex�cuter lors de l'appui sur le bouton browse*/
	private void actionBrowse(){
		String [] tab = null;
		final ListView list = (ListView)findViewById(R.id.listBrowseFile);
		final RelativeLayout relativeControl = (RelativeLayout)findViewById(R.id.relativeControl);
		final RelativeLayout relativeFile = (RelativeLayout)findViewById(R.id.relativeFile);
		final Button backButton = (Button)findViewById(R.id.backBrowse);
		backButton.setVisibility(View.VISIBLE);
		relativeControl.setVisibility(View.INVISIBLE);
		relativeFile.setVisibility(View.VISIBLE);
    	
		cancelButton.setClickable(true);
    	cancelButton.setVisibility(View.VISIBLE);
    	informationFile.setVisibility(View.VISIBLE);
    	
		LogHelper.information(logTag, "get video in " + Environment.getExternalStorageDirectory().getPath());
		try{
        	tab = getVideo(Environment.getExternalStorageDirectory().getPath()+"/Movies");
        
        	  ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,tab);
              list.setAdapter(adapter);
              list.setClickable(true);
              list.setOnItemClickListener(new OnItemClickListener() {
           	   public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
           		    pathVideo = (String) list.getItemAtPosition(position);
       				LogHelper.information("actionBrowse()", "film choisi : "+pathVideo);
       				modeButton.setText("Server");
       				isServer = true;
       				informationFile.setText("You chose the file : "+pathVideo);       				
       				startVideoPlayer(Environment.getExternalStorageDirectory().getPath()+"/Movies/"+pathVideo);
       				relativeControl.setVisibility(View.VISIBLE);
       				relativeFile.setVisibility(View.INVISIBLE);
       				browseButton.setVisibility(View.INVISIBLE);
       				browseButton.setClickable(false);
           		  }
       	});
              backButton.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View v) {
				LogHelper.information("actionBrowse()", "appui sur back du browseFile");
				modeButton.setText("Client");
				backButton.setVisibility(View.INVISIBLE);
				relativeControl.setVisibility(View.VISIBLE);
				relativeFile.setVisibility(View.INVISIBLE);
				cancelButton.setVisibility(View.INVISIBLE);
				cancelButton.setClickable(false);
				}
			});
		}
        catch (Exception e){
        	tab[0] = "Il y a un probleme avec la localisation de la carte memoire";
        }
	}
	
	public String[] getVideo(String rep){
	    	File repertoire = new File(rep);
	    	File tmp[]=repertoire.listFiles(videoFilter);/*ajouter videoFilter en param�tre pour ajouter le filtre*/
	    	String ret[] = new String [tmp.length];
	    	for(int i=0;i<tmp.length;i++){
	    		
	    		ret[i]=tmp[i].getName();
	    	}
	    			return ret;
    }
	 
	private static FilenameFilter videoFilter = new FilenameFilter() {
			public boolean accept(File dir, String name) {
				return (name.endsWith(".mkv") || name.endsWith(".mp4") || name.endsWith(".avi"));
			}
	  };
	
}
